package com.yupi.springbootinit.bizmq;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.BiChatManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.yupi.springbootinit.bizmq.BIMqConstant.BI_QUEUE_NAME;

@Component
@Slf4j
public class BiMessageConsumer {
    
    @Resource
    private ChartService chartService;

    @Resource
    private BiChatManager biChatManager;
    
    @SneakyThrows
    @RabbitListener(queues = BI_QUEUE_NAME, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
        log.info("receiveMessage message = {}",message);
        if (StringUtils.isBlank(message)) {
            // 如果失败，消息拒绝
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        
        // 先修改图表任务状态为 “执行中”。等执行成功后，修改为 “已完成”、保存执行结果；执行失败后，状态修改为 “失败”，记录任务失败信息。
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
            return;
        }

        //调用AI
        String result = biChatManager.chatSyncTest(buildUserInput(chart));
        //对返回结果拆分
        String resRule = "分析结论：([\\s\\S]*)前端图表";
        String genResult = matcher(resRule,result);

        String chartRule = "```json([\\s\\S]*)```";
        String genChart = matcher(chartRule,result);

        //AI处理完成后,更新图表
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        updateChartResult.setStatus("succeed");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
        }
        //消息确认
        channel.basicAck(deliveryTag,false);
    }
    
    public String buildUserInput(Chart chart){
        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        String userGoal = chart.getGoal();
        //分析目标
        userInput.append("分析需求:").append(userGoal).append("\n");
        //图表类型
        userInput.append("图表类型:").append(chart.getChartType()).append("\n");
        //原始数据
        userInput.append("原始数据:").append("\n");
        //传入文件,获取原始数据
        userInput.append(chart.getChartData()).append("\n");
        
        return userInput.toString();
    }

    //文本匹配
    public String matcher(String rule,String result){
        Pattern resPattern = Pattern.compile(rule);
        Matcher resMatcher = resPattern.matcher(result);
        if (resMatcher.find()){
            return resMatcher.group(1).trim();
        }else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文本查找失败");
        }
    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage("execMessage");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }
    
    
    
}
